// String -> MD5 string utility
// Copyright 2005 (C) Ralph Thomas

#include <util/md5.h>
#include <adobe/md5.hpp>

namespace util {
	static std::string digest_to_string( const adobe::md5_t::digest_t& digest ) {
		std::string output;
		for( unsigned int i = 0; i < digest.size(); i++ ) {
			char buf[3];
			snprintf( buf, 3, "%02x", digest[i] );
			output += buf;
		}
		return output;
	}
	std::string md5( const std::string& source ) {
		//
		// First create a digest of the source string.
		//
		char* sourceC = new char[source.size()];
		memcpy( sourceC, source.c_str(), source.size() );
		adobe::md5_t::digest_t digest( adobe::md5( sourceC, source.size() ) );
		delete[] sourceC;
		//
		// Convert the binary digest to a hex string.
		//
		return digest_to_string( digest );
	}
	std::string md5( std::streambuf* source, unsigned int count ) {
		//
		// XXX: Ask Foster about how to do it this (better) way.
		//
/*		adobe::md5_t hasher;
		int read( 0 );
		char buffer[4096];
		
		if( !source ) return std::string();

		while( (read == 4096) && (count > 0) ) {
			read = 4096;
			if( read > count ) read = count;
			read = source->sgetn( buffer, read );
			hasher.update( buffer, read );
		}
		return digest_to_string( hasher.final() );*/
		int read( count );
		char* buffer = new char[count];
		read = source->sgetn( buffer, read );
		adobe::md5_t::digest_t digest( adobe::md5( buffer, read ) );
		return digest_to_string( digest );
	}
};

